package com.servengine.localizame;

import com.servengine.struts.ClientAction;

import com.servengine.user.User;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class Actions extends ClientAction
{
	private static org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog(Actions.class.getName());
	LocalizameManagerLocal localizameManager;
	
	public void initAction(javax.naming.Context context)
	{
	  try
	  {
	    localizameManager=(LocalizameManagerLocal)context.lookup("LocalizameManager/local");
	  } catch (Exception e)
	  {
	    log.error(e.getMessage(), e);
	    throw new IllegalStateException(e.getMessage());
	  }
		log.info(getClass().getName() + " initialized");
	}

	public ActionForward unspecified(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException,ServletException
	{
		try
		{
			User user = getUserSession(request).getUser();
			LocalizamePosicion ultimaPosicion = localizameManager.getUltimaPosicion(user);
			if (ultimaPosicion!=null)
			{
				request.setAttribute("ultimaPosicion",ultimaPosicion);
				request.setAttribute("posiblesAmiguitos",localizameManager.getPosiblesAmiguitos(ultimaPosicion));
			}
		  return mapping.findForward("success");
		} catch (Throwable e)
		{
			log.error(e.getMessage(),e);
			saveErrors(request,getErrorsFromException(e));
			return mapping.findForward("error");
		}
	}
	
	public ActionForward setPosition(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException,ServletException
	{
		try
		{
			User user = getUserSession(request).getUser();
			LocalizameConexion localizameConexion = new LocalizameConexion(user,((LocalizameForm)form).getCodigo());
			LocalizamePosicion posicion = localizameConexion.getPosicion();
		  if (posicion==null)
				posicion = localizameConexion.getPosicion(); //Probamos otra vez. Con frecuencia falla la primera vez.
			if (posicion==null)
				return mapping.findForward("errorLocalizame");
			localizameManager.store(posicion);
			return unspecified(mapping,form,request,response);
		} catch (Throwable e)
		{
			log.error(e.getMessage(),e);
			saveErrors(request,getErrorsFromException(e));
			return mapping.findForward("error");
		}
	}
	

}
